package com.xcf.controller.business.settlement;

import cn.com.xcf.dao.model.TCheckIncome;
import cn.com.xcf.dao.model.TCheckIncomeExample;
import cn.com.xcf.service.TCheckIncomeService;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.TypeReference;
import com.xcf.controller.base.BaseController;
import com.xcf.controller.base.CommonResponse;
import com.xcf.controller.base.ExportDataHandler;
import com.xcf.entity.Page;
import com.xcf.entity.system.User;
import com.xcf.util.JsonConvertPageData;
import com.xcf.util.Jurisdiction;
import com.xcf.util.PageData;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 收款对账
 * @author WongBin
 */
@Controller
@RequestMapping(value="/incomeAcct")
public class CheckIncomeController extends BaseController implements ExportDataHandler{
	
	String menuUrl = "/incomeAcct/index"; //菜单地址(权限用)
    private static final String base = "/business/settlement/";

	@Autowired
	private TCheckIncomeService checkService;

    @RequestMapping(value = "/index")
    public ModelAndView cost(Page page, HttpServletRequest req){
        ModelAndView mv = this.getModelAndView();
        mv.setViewName(base.concat("check_income_index"));
        mv.addObject("pd", new HashMap());
        return mv;
    }
	@RequestMapping(value="/listUndoList",method = RequestMethod.POST)
    //@ResponseBody
	public Object getUndoList(Page page, HttpServletRequest req) throws Exception{
		Map param = getParams(req);//new PageData(req);
		TCheckIncomeExample e = new TCheckIncomeExample();
		e.createCriteria();
		e.setPage(page);
		handlePageParams(param,e.getPage());
        ModelAndView mv = getModelAndView();
        try{
            List ret = checkService.getCheckUndoList(e,param,e.getPage());
            //PageData pd = getPageData();
            mv.addObject("dataList",ret);
            mv.addObject("page",e.getPage());
            mv.addObject("QX", Jurisdiction.getHC());//按钮权限
			mv.setViewName(base.concat("panel/check_income_item_left"));
			return mv;
            /* Map map = new HashMap();
            map.put("list",ret);
            map.put("total",page.getTotalResult());
            PageInfo d = new PageInfo(ret);
            handlePage(page, d);*/
            //return CommonResponse.success(map);
        } catch(Exception ex){
            log.error("query-check-error:"+param,ex);
        }
        return CommonResponse.fail();
	}

	/**
	 * save
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/append",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse append(
			@RequestParam String checkId,
			@RequestParam String undoList,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();

		try {
			assert undoList!=null && undoList.length()>0 && !StringUtils.isEmpty(checkId);
			List list = Arrays.asList(undoList.split(","));
			checkService.addToCheckList(checkId, list, operator);
			response.initSuccess();
		}catch (Exception ex){
			log.error("append-checklist-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}

	/**删除
	 * @throws Exception
	 */
	@RequestMapping(value="/cancel",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse cancel(@RequestParam Object id,
						   HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
		try {
			assert id!=null ;
			String keys = id+"";
			for(String item : keys.split(",")) {
				checkService.cancelRecord(Long.valueOf(item), operator);
			}
			response.initSuccess();
		}catch (Exception ex){
			log.error("cacel-checklist-error:{}",id,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}

	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/genCheckRecord",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse genRecord(
			@RequestParam String undoList,
            @RequestParam String depart,
            @RequestParam String totalPrice,                  
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		User operator = getLoginUser(req,res);//.getUSER_ID();
		
		JSONObject jb = JSONObject.fromObject(totalPrice);
		Map<String, Object> map = (Map<String, Object>)jb;
		try {
			assert undoList.length()>0;
            operator.setSKIN(depart);
			checkService.genCheckRecord(map,Arrays.asList(undoList.split(",")),operator);
			response.initSuccess();
		}catch (Exception ex){
			log.error("add-checklist-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getCheckList",method = RequestMethod.POST)
    //@ResponseBody
	public Object getCheckList(
			TCheckIncome item,Page page,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		//CommonResponse response = new CommonResponse();
		ModelAndView mv = getModelAndView();
		String operator = getLoginUser(req,res).getUSER_ID();
        handlePageParams(getParams(req),page);
		//Page page = getPage();
		try {
			List data = checkService.getCheckList(item,null,page);
			
			mv.addObject("checkList",data);
			mv.addObject("page",page);
			mv.addObject("QX", Jurisdiction.getHC());//按钮权限
			mv.setViewName(base.concat("panel/check_income_item_rt"));
            /*PageInfo d = new PageInfo(data);
            handlePage(page, d);
            return CommonResponse.success(d);*/
		}catch (Exception ex){
			log.error("get-checklist-error:{}",item,ex);
			//response.initSysError(ex.getMessage());
		}
		return mv;
	}
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/invalid",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse invalid(
			@RequestParam String checkId,
			@RequestParam String undoList,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
		try {
			assert checkId!=null && checkId.length()>0 && undoList!=null && undoList.length()>0;
			checkService.invalidCheckRecordDetails(checkId,Arrays.asList(undoList.split(",")),operator);
			response.initSuccess();
		}catch (Exception ex){
			log.error("invalidate-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}
	@RequestMapping(value="/listItems",method = RequestMethod.POST)
	//@ResponseBody
	public ModelAndView listItems(
			@RequestParam String checkId,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		//CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
        ModelAndView view = getModelAndView();
		try {
			assert checkId!=null && checkId.length()>0 /*&& undoList!=null && undoList.length()>0*/;
			Object data = checkService.listItemsByCheckId(checkId);
			/*response.setData(data);
			response.initSuccess();*/
			view.addObject("data",data);
            view.addObject("QX", Jurisdiction.getHC());//
			view.setViewName(base.concat("panel/check_income_item_rb"));
		}catch (Exception ex){
			log.error("list-items-error:{}",checkId,ex);
			//response.initSysError(ex.getMessage());
		}
		return view;
	}

	@Override
	public List getData(String type, Map param, Page page) {
		if("checkIncomeUndoList".equalsIgnoreCase(type)){
			List ret = checkService.getCheckUndoList(param,new HashMap(1),page);
			return ret;
		}
		if("checkIncomeList".equalsIgnoreCase(type)){
			TCheckIncome item = new TCheckIncome();
			List data = checkService.getCheckList(item,null,page);
			return data;
		}
		return null;
	}

	@Override
	public String getService() {
		return getClass().getSimpleName();
	}

	@Override
	public Map<String, String> setNames() {
		Map m = new HashMap(6);
		m.put("checkIncomeUndoList","check_income_undo.xls");
		m.put("checkIncomeUndoListName","未收款对账费用明细");
		m.put("checkIncomeUndoListModule",getService());

		m.put("checkIncomeList","check_income_done.xls");
		m.put("checkIncomeListName","收款对账单明细");
		m.put("checkIncomeListModule",getService());
		return m;
	}

	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/export",method = RequestMethod.GET)
	public CommonResponse export(@RequestParam String expType,
								 HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
		Map param = getParams(req);
		try {
			List data = null;
			if("01".equals(expType)) {
				data = checkService.exportCheckList(param);
			}
			if("02".equals(expType)){
				data = checkService.exportUndoList(param);
			}
			//TODO导出文件生成
			response.initSuccess();
		}catch (Exception ex){
			log.error("exp-error:{}",expType,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}
	
	@RequestMapping(value = "/invoiceApp")
    public ModelAndView app(Page page, HttpServletRequest req){
		PageData pd = new PageData();
		pd =this.getPageData();		
        ModelAndView mv = this.getModelAndView();
        mv.setViewName(base.concat("check_income_invoice_app"));
        mv.addObject("pd",pd);
        return mv;
    }
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getInvoiceDept",method = RequestMethod.POST)
	@ResponseBody
	public void invoiceDept(HttpServletRequest req,HttpServletResponse res,Page page) throws Exception{
		CommonResponse response = new CommonResponse();
		
		try {
		
			
			List<PageData>	deptList = checkService.getInvoiceDept(page);	
			
			JSONArray json = new JSONArray();
            for(PageData p : deptList){
                JSONObject jo = new JSONObject();
                jo.put("check_dept", p.getString("check_dept"));	
                jo.put("check_dept_name", p.getString("check_dept_name"));
                json.add(jo);
            }
             
//            String operator = getLoginUser(req,res).getUSER_ID();
//            ModelAndView view = getModelAndView();
//    	
//            view.addObject("checkList",json);
//            view.addObject("page",page);
//            view.addObject("QX", Jurisdiction.getHC());//按钮权限
//            view.setViewName(base.concat("check_income_invoice_app")); 
            res.setContentType("text/html; charset=utf-8");
			res.getWriter().write(json.toString());				
			res.getWriter().flush();
            
			
		}catch (Exception ex){
			log.error("invalidate-error:{}",null,ex);
			response.initSysError(ex.getMessage());
		}
		//return response;
	}
	
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getFeeList",method = RequestMethod.POST)
	@ResponseBody
	public void getFeeNameList(HttpServletRequest req,HttpServletResponse res,Page page) throws Exception{
		CommonResponse response = new CommonResponse();
		
		try {
			 PageData pd = this.getPageData();
			
			
			
			List<PageData>	feeList = checkService.getFeeList(pd);	
			
			JSONArray json = new JSONArray();
			int i=0;
            for(PageData p : feeList){
            	
                JSONObject jo = new JSONObject();
                jo.put("index", i++);
                jo.put("ID",  p.get("ID"));
                jo.put("currency", p.get("CURRENCY"));
                jo.put("price", p.get("PRICE"));
                jo.put("taxRate", p.get("TAX_RATE"));
                jo.put("costName", p.getString("COST_NAME"));
                json.add(jo);
            }
             

            res.setContentType("text/html; charset=utf-8");
			res.getWriter().write(json.toString());				
			res.getWriter().flush();
            
			
		}catch (Exception ex){
			log.error("invalidate-error:{}",null,ex);
			response.initSysError(ex.getMessage());
		}
		//return response;
	}
	@RequestMapping(value="/getFeeRelativeList",method = RequestMethod.POST)
	@ResponseBody
	public void getFeeRelativeList(HttpServletRequest req,HttpServletResponse res,Page page) throws Exception{
		CommonResponse response = new CommonResponse();
		
		try {
			 PageData pd = this.getPageData();
			
			
			int index = Integer.parseInt(pd.get("index").toString());
			List<PageData>	feeList = checkService.getFeeList(pd);	
			
			JSONArray json = new JSONArray();
			int i=-1;
            for(PageData p : feeList){
            	 i++;
            	if(index==i)
            	{
	                JSONObject jo = new JSONObject();
	                jo.put("index", i);
	                jo.put("currency", p.get("CURRENCY"));
	                jo.put("price", p.get("PRICE"));
	                jo.put("taxRate", p.get("TAX_RATE"));
	                jo.put("costName", p.getString("COST_NAME"));
	                json.add(jo);
	                break;
            	}
            }
             

            res.setContentType("text/html; charset=utf-8");
			res.getWriter().write(json.toString());				
			res.getWriter().flush();
            
			
		}catch (Exception ex){
			log.error("invalidate-error:{}",null,ex);
			response.initSysError(ex.getMessage());
		}
		//return response;
	}
	@RequestMapping(value="/getTaxRateAmountList",method = RequestMethod.POST)
	@ResponseBody
	public void taxRateAmountList(
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		//CommonResponse response = new CommonResponse();
		PageData pd = this.getPageData();
		String operator = getLoginUser(req,res).getUSER_ID();
		String checkId=pd.getString("checkId");
		
        
			
			List<PageData> data = checkService.listItemsByCheckId(checkId);
			
			try{
				
			JSONArray json = new JSONArray();
            for(HashMap p : data){
                JSONObject jo = new JSONObject();
                if("RMB".equals(p.get("CURRENCY")))
                {
                	double amount=Double.parseDouble(p.get("TAX_PRICE").toString())*Double.parseDouble(p.get("CONTAINER_NUM").toString());
                	jo.put("costName", p.get("COST_NAME"));
	                jo.put("taxRate", p.get("TAX_RATE"));
	                jo.put("amount",amount);
	                json.add(jo);
                }
            }
             

            res.setContentType("text/html; charset=utf-8");
			res.getWriter().write(json.toString());				
			res.getWriter().flush();

		}catch (Exception ex){
			log.error("list-items-error:{}",checkId,ex);
			
		}

	}
	
	
	@RequestMapping(value="/getExchangeRate",method = RequestMethod.POST)
	@ResponseBody
	public void getExchangeRate(
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		
		PageData pd = this.getPageData();
		PageData data = (PageData)checkService.getExchangeRate();
			
			try{

            res.setContentType("text/html; charset=utf-8");
			res.getWriter().write(data.get("rate").toString());				
			res.getWriter().flush();

		}catch (Exception ex){
			//log.error("list-items-error:{}",checkId,ex);
			
		}

	}
	@RequestMapping(value="/getopenTicketFeeType",method = RequestMethod.POST)
	@ResponseBody
	public void getopenTicketFeeType(
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		List<Map<String,Object>> list = (List<Map<String,Object>>)checkService.getopenTicketFeeType();
			
			try{
				JSONArray json = new JSONArray();
	            for(Map<String,Object> p : list){
	                JSONObject jo = new JSONObject();
                	jo.put("id", p.get("id"));
                	jo.put("feeName", p.get("fee_name"));
                	jo.put("taxRate", p.get("tax_rate"));
	                json.add(jo);
	            }
	
	            res.setContentType("text/html; charset=utf-8");
				res.getWriter().write(json.toString());						
			res.getWriter().flush();

		}catch (Exception ex){
			 log.error("list-items-error:{}","getopenTicketFeeType",ex);
			
		}

	}
	
	@RequestMapping(value="/getOpenTicketFeeItems",method = RequestMethod.POST)
	@ResponseBody
	public void getOpenTicketFeeItems(
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		    
		    
		     PageData pd = this.getPageData();
			 List<Map<String,Object>> feeItems = checkService.getOpenTicketFeeItems(pd.get("checkId"));
				
			 try{
					JSONArray json = new JSONArray();
		            for(Map p : feeItems){
		            	
		            	if(p==null) continue;
		                JSONObject jo = new JSONObject();		                
	                	jo.put("taxRate", p.get("taxRate"));
	                	jo.put("feeName", p.get("feeName"));
	                	jo.put("taxPrice", p.get("taxPrice"));
	                	jo.put("containerNum", p.get("containerNum"));
	                	jo.put("currency", p.get("currency"));
	                	
		                json.add(jo);
		            }
		
		            res.setContentType("text/html; charset=utf-8");
					res.getWriter().write(json.toString());						
				    res.getWriter().flush();

			}catch (Exception ex){
				 log.error("list-items-error:{}","getOpenTicketFeeItems",ex);
			}
				
			
	}
	@RequestMapping(value="/getChangeTicketFee",method = RequestMethod.POST)
	@ResponseBody
	public void getChangeTicketFee(
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		
		try{
	     //if(req.getAttribute("id")==null) return;
	     PageData pd = this.getPageData();
		 int id = Integer.parseInt(pd.getString("id"));
		
		double taxRate = checkService.getChangeTicketFee(id);
			
			
	                JSONObject jo = new JSONObject();
                	jo.put("taxRate", taxRate);
	             

	            res.setContentType("text/html; charset=utf-8");
				res.getWriter().write(jo.toString());						
			res.getWriter().flush();

		}catch (Exception ex){
			 log.error("list-items-error:{}","getopenTicketFeeType",ex);
			
		}

	}
	@RequestMapping(value="/saveInvoiceApp",method = RequestMethod.POST)
	@ResponseBody
	public void saveInvoiceApp(
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		
		PageData pd = this.getPageData();

		  double usdAmount=0;
		  double rmbAmount=0;
		  double usdRate = Double.parseDouble(pd.get("exchangeRate").toString());
		 // {0:装卸服务,1:0.06,2:32,3:21,4:RMB},{0:箱管代理费,1:0.06,2:1200,3:32,4:USD}
		  //0发票名目,1税率，2,含税金额,3箱量4币种
		  String json = pd.getString("json");
		  JSONArray jsonArr = JSONArray.fromObject("["+json+"]");
		 
		  
		  String curreny = pd.get("curreny").toString();
		  String [] arr = curreny.split(",");
		  String deptId = pd.get("dept_id").toString();
		  String deptName= pd.get("dept_name").toString();
		  String checkId = pd.get("checkId").toString();
		  String checkCode =  pd.get("checkCode").toString();
		  String invoiceTypeId = pd.get("invoiceType").toString();
		  String invoiceType = pd.get("invoiceTypeTxt").toString();
		  pd.put("invoiceTypeId", invoiceTypeId);
		  pd.put("invoiceType", invoiceType);
		  String remark = pd.get("remark").toString();
		  String invoiceFeeId = pd.get("invoiceFeeId").toString();
		  String invoiceFeeName = pd.get("invoiceFeeName").toString();
		  pd.put("appDept", deptId);
		  pd.put("appDeptName", deptName);
		  User operator = getLoginUser(req,res);		  
		  pd.put("appPerson",operator.getUSER_ID());
		  pd.put("appPersonName",operator.getNAME());		  
		  pd.put("settlementDeptId",deptId);
		  pd.put("settlementDept",deptName);
		  
       
    	Map<String, Object> param = new HashMap<String, Object>();
    	param.put("invoiceAppCode", null);
    	try{
			
		  /**
		   * 人民币和美元各自生成申请
		   * **/
		  for(int i=0;i<arr.length;i++){
			  
			  if("RMB".equals(arr[i]))
			  {
				  
				 rmbAmount =Double.parseDouble(pd.get("rmbAmount").toString());
				 String invoiceAppCode=checkService.getInvoiceAppCode(param).toString();
				 pd.put("invoiceAppCode", invoiceAppCode);
				 pd.put("exchangeRate",1);				 
				 pd.put("currency","RMB");	
				 checkService.insertInvoiceApp(pd);
				 
				  for(int k=0;k<jsonArr.size();k++)
				  {
					if(k==i){
					    Object o= jsonArr.get(i);
					    JSONObject jsonObject2=JSONObject.fromObject(o);
					    
					    String item = jsonObject2.get("0").toString();
					    String taxRate = jsonObject2.get("1").toString();
					    String taxPrice = jsonObject2.get("2").toString();
					    String containerNum = jsonObject2.get("3").toString();
					    String currency =   jsonObject2.get("4").toString();
					    Map<String,Object> map = new HashMap<String,Object>();
					    map.put("item", item);
					    map.put("taxRate", taxRate);
					    map.put("taxPrice", taxPrice);
					    map.put("containerNum", containerNum);
					    map.put("currency", currency);
					    map.put("invoiceAppCode", invoiceAppCode);
					    map.put("exchangeRate", usdRate);
					    map.put("checkCode", checkCode);
					    
					    if("RMB".equals(currency))
					    {
					    	checkService.insertInvoiceAppItem(map);
					    }
					}
				   
				    
				  }
				 
			  }
			  else
			  {
				 usdAmount =Double.parseDouble(pd.get("usdAmount").toString()); 
				 String invoiceAppCode=checkService.getInvoiceAppCode(param).toString();
				 pd.put("invoiceAppCode", invoiceAppCode);
				 pd.put("exchangeRate",usdRate);	
				 pd.put("currency","USD");	
				 checkService.insertInvoiceApp(pd);
				 for(int j=0;j<jsonArr.size();j++)
				  {
					if(j==i){
					    Object o= jsonArr.get(i);
					    JSONObject jsonObject2=JSONObject.fromObject(o);
					    
					    String item = jsonObject2.get("0").toString();
					    String taxRate = jsonObject2.get("1").toString();
					    String taxPrice = jsonObject2.get("2").toString();
					    String containerNum = jsonObject2.get("3").toString();
					    String currency =   jsonObject2.get("4").toString();
					    
					    Map<String,Object> map = new HashMap<String,Object>();
					    map.put("item", item);
					    map.put("taxRate", taxRate);
					    map.put("taxPrice", taxPrice);
					    map.put("containerNum", containerNum);
					    map.put("currency", currency);
					    map.put("invoiceAppCode", invoiceAppCode);
					    map.put("exchangeRate", 1);
					    map.put("checkCode", checkCode);
					    if("USD".equals(currency))
					    {
					    	checkService.insertInvoiceAppItem(map);
					    }
					}
				    
				  }
				
			  }
		  }
		  
		
		
		//checkService.updateDivFeeItems(divList);
		
			
            res.setContentType("text/html; charset=utf-8");
			res.getWriter().write("sucess");				
			res.getWriter().flush();

		}catch (Exception ex){
			log.error("list-items-error:{}",checkId,ex);
			
		}

	}
	
	
}
